var ws;
var account;
$(document).ready(function () {
    account = "testUser-"+randomNum(0,1000)
    ws = new WebSocket('ws://192.168.1.32:8888/')
    ws.binaryType = "arraybuffer"

//监听是否连接成功
    ws.onopen = function () {
        console.log('ws连接状态：' + ws.readyState);
        loginWebSocket(account)
    }
// 接听服务器发回的信息并处理展示
    ws.onmessage = function (ev) {
        var view = new DataView(ev.data);
        var len = view.getUint16(0,false)
        var msgId = view.getUint32(2,false)
        var buffer = new ArrayBuffer(len);
        var resultView = new DataView(buffer);
        for (var i = 0; i < len; i++) {
            resultView.setUint8(i, view.getUint8(i + 6));
        }
        switch (msgId) {
            case 2:
                getLocation(resultView.buffer)
            break;
        }
    }
// 监听连接关闭事件
    ws.onclose = function () {
        // 监听整个过程中websocket的状态
        console.log('ws连接状态：' + ws.readyState);
    }
// 监听并处理error事件
    ws.onerror = function (error) {
        console.log(error);
    }
});

function onSend(message, msgId){
    var buffer = new ArrayBuffer(message.serializeBinary().length + 6); // 前两位留给消息体长度，后四位留给msg_id
    var view = new DataView(buffer);
    view.setUint16(0, message.serializeBinary().length);
    view.setUint32(2, msgId)
    for (var i = 0; i < message.serializeBinary().length; i++) {

        view.setUint8(i + 6, message.serializeBinary()[i]);
    }
    ws.send(view);
}

function randomNum(minNum,maxNum){
    switch(arguments.length){
        case 1:
            return parseInt(Math.random()*minNum+1,10);
            break;
        case 2:
            return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10);
            break;
        default:
            return 0;
            break;
    }
}